<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">品种名称</label>
        <el-input v-model="query.stockName" clearable placeholder="品种名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">品种代码</label>
        <el-input v-model="query.stockCode" clearable placeholder="品种代码" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <date-range-picker
          v-model="query.stockType"
          class="date-item"
        />

        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="850px">
        <el-form ref="form" :model="form" inline :rules="rules" size="small" label-width="98px">
          <el-form-item label="品种名称" prop="stockName">
            <el-input v-model="form.stockName" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="品种代码" prop="stockCode">
            <el-input v-model="form.stockCode" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="品种类型" prop="stockType">
            <el-select v-model="form.stockType" filterable placeholder="请选择" style="width: 270px;">
              <el-option
                v-for="item in dict.stock_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="买入价格" prop="buyPrice">
            <el-input v-model="form.buyPrice" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="卖出价格" prop="sellPrice">
            <el-input v-model="form.sellPrice" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="买入时间" prop="buyTime">
            <el-date-picker v-model="form.buyTime" type="datetime" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="卖出时间" prop="sellTime">
            <el-date-picker v-model="form.sellTime" type="datetime" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="持有数量" prop="holdNum">
            <el-input-number v-model="form.holdNum" style="width: 270px;" controls-position="right" :min="1" :max="10" />
          </el-form-item>

          <el-form-item label="赚取差价" prop="earnMoney">
            <el-input v-model="form.earnMoney" style="width: 270px;" />
          </el-form-item>
          <el-form-item label="分享心得">
            <Editor ref="editor" v-model="form.shareMood" style="width:540px;" />
            <!-- <el-input v-model="form.shareMood" :rows="3" type="textarea" style="width: 270px;" /> -->
          </el-form-item>
          <el-form-item label="图片" style="width: 800px;">
            <el-upload
              :action="imagesUploadApi + '?name=' + form.picName"
              list-type="picture-card"
              :limit="3"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="onBeforeUpload"
              :headers="headers"
              :file-list="form.pictureList"
              accept="image/jpeg,image/jpg,image/png"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="stockName" label="品种名称" align="center" />
        <el-table-column prop="stockCode" label="品种代码" align="center" />
        <el-table-column prop="stockType" label="品种类型" align="center">
          <template slot-scope="scope">
            {{ dict.label.stock_type[scope.row.stockType] }}
          </template>
        </el-table-column>
        <el-table-column prop="buyPrice" label="买入价格" align="center" />
        <el-table-column prop="sellPrice" label="卖出价格" align="center" />
        <el-table-column prop="buyTime" label="买入时间" align="center" />
        <el-table-column prop="sellTime" label="卖出时间" align="center" />
        <el-table-column prop="holdNum" label="持有数量" align="center" />

        <el-table-column prop="earnMoney" label="赚取差价" align="center" />
        <el-table-column prop="path" label="预览图">
          <template slot-scope="scope">
            <div v-if="scope.row.picPath">
              <div
                v-for="(item) in scope.row.picPath.split('|')"
                :key="item"
              >
                <el-image
                  v-if="item"
                  :src=" baseApi + item"
                  :preview-src-list="[baseApi + item]"
                  fit="contain"
                  lazy
                  class="el-avatar"
                >
                  <div slot="error">
                    <i
                      class="el-icon-document"
                    />
                  </div>
                </el-image>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','stock:edit','stock:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"

              :permission="permission"
            />

          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import crudStock from '@/api/stock'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import DateRangePicker from '@/components/DateRangePicker'
import Editor from '@/views/components/MyEditor'

const defaultForm = {
  id: null,
  stockName: null,
  stockCode: null,
  stockType: null,
  buyPrice: null,
  sellPrice: null,
  buyTime: null,
  sellTime: null,
  holdNum: null,
  holdTime: null,
  picName: null,
  picPath: null,
  earnMoney: null,
  shareMood: null,
  pictureList: [],
  delFlag: 0 }
export default {
  name: 'Stock',
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker, Editor },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['stock_type'],
  cruds() {
    return CRUD({ title: '投资品种', url: 'api/stock', idField: 'id', sort: 'id,desc', crudMethod: { ...crudStock }})
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      permission: {
        add: ['admin', 'stock:add'],
        edit: ['admin', 'stock:edit'],
        del: ['admin', 'stock:del']
      },
      headers: { 'Authorization': getToken() },
      rules: {
        stockName: [
          { required: true, message: '品种名称不能为空', trigger: 'blur' }
        ],
        stockCode: [
          { required: true, message: '品种名称不能为空', trigger: 'blur' }
        ],
        stockType: [
          { required: true, message: '品种类型不能为空', trigger: 'blur' }
        ],

        buyPrice: [
          { required: true, message: '买入价格不能为空', trigger: 'blur' }
        ],
        // sellPrice: [
        //   { required: true, message: '卖出价格不能为空', trigger: 'blur' }
        // ],
        buyTime: [
          { required: true, message: '买入时间不能为空', trigger: 'blur' }
        ],
        // sellTime: [
        //   { required: true, message: '卖出时间不能为空', trigger: 'blur' }
        // ],
        holdNum: [
          { required: true, message: '持有数量不能为空', trigger: 'blur' }
        ]

        // earnMoney: [
        //   { required: true, message: '赚取差价不能为空', trigger: 'blur' }
        // ]
      },
      queryTypeOptions: [
        { key: 'stockName', display_name: '品种名称' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi'
    ])
  },
  mounted() {
    console.log(this.crud.data)
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.picPath) {
        var arr = this.form.picPath.split('|')
        for (var i = 0; i < arr.length; i++) {
          if (arr[i]) {
            var array = arr[i].split('/')
            this.form.pictureList.push({
              'url': this.baseApi + arr[i],
              response: { 'realName': array[3], 'type': array[2] }
            })
          }
        }
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    // 图片上传超出最大数量
    handleExceed(file, fileList) {
      this.$message({
        message: '每条最多上传三张图片',
        center: true,
        type: 'warning'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.picName = file.name
      return isIMAGE && isLt1M
    },
    handlePreview(file) {
      var a = this.$refs['downloadA']
      a.href = this.baseApi + '/file/' + file.response.type + '/' + file.response.realName
      a.click()
    }

  }
}
</script>

<style scoped>

</style>
